package com.wy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wy.common.R;
import com.wy.entity.Role;
import com.wy.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author 王昭贵
 * @since 2023-01-12
 */
@Slf4j
@RestController
@RequestMapping("/role")
public class RoleController {
    @Resource
    private IRoleService roleService;

    // 新增或者更新
    @PostMapping
    public R save(@RequestBody Role role) {
        roleService.saveOrUpdate(role);
        if(role.getId()==null){
            return R.success("新增角色成功");
        }
        return R.success("修改角色成功");
    }

    /****
     * 删除角色
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id) {
        roleService.removeById(id);
        return R.success("删除角色成功");
    }

    /****
     * 查询所有角色列表
     * @return
     */
    @GetMapping
    public R findAll() {
        List<Role> list = roleService.list();
        return R.success(roleService.list());
    }

    /****
     * 根据id获取角色信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R findOne(@PathVariable Integer id) {
        return R.success(roleService.getById(id));
    }

    /****
     * 角色列表分页
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam String name) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        queryWrapper.orderByDesc("id");
        return R.success(roleService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }
    /**
     * 绑定角色和菜单的关系
     * @param roleId 角色id
     * @param menuIds 菜单id数组
     * @return
     */
    @PostMapping("/roleMenu/{roleId}")
    public R roleMenu(@PathVariable Integer roleId, @RequestBody List<Integer> menuIds) {
        roleService.setRoleMenu(roleId, menuIds);
        return R.success("角色分配菜单成功");
    }

    /****
     *  分配菜单
     * @param roleId
     * @return
     */
    @GetMapping("/roleMenu/{roleId}")
    public R getRoleMenu(@PathVariable Integer roleId) {
        return R.success( roleService.getRoleMenu(roleId));
    }
}

